<!DOCTYPE html>
<html lang="en">
<head>
	<meta charset="UTF-8">
	<title>137-动画-匀速动画-封装函数.html</title>
	<style>
		*{
			margin: 0;
			padding: 0;
		}
		.container{
			width: 400px;
			margin: 100px auto;
		}
		.box{
			width: 100px;
			height: 100px;
			line-height: 100px;
			margin-top: 20px;
			background-color: skyblue;
			opacity: 0.3;
			text-align: center;
		}
		.box:last-child{
			opacity: 0.2;
		}
	</style>
</head>
<body>
	<div class="container">
		<div class="box" id="box1"></div>
		<div class="box" id="box2"></div>
		<div class="box" id="box3"></div>
		
	</div>
</body>
<script>

	function animation(obj,attr,Target){
		//防止用户多次点击
		clearInterval(obj.timer);
		obj.timer = setInterval(function(){
		//获取当前该属性的值
			var currentVal = parseFloat(getComputedStyle(obj,false)[attr]);
		//处理透明度，将其转化为百分制数
			if(attr == "opacity"){
				currentVal = Math.round(currentVal*100);		
			}
		//判断速度的取值
			if(currentVal > Target){
				iSpeed = -10;
			}else{
				iSpeed = 10;
			}	
		//动画的终止条件
			if(Math.abs(Target - currentVal) < Math.abs(iSpeed)){
		//判断透明度和非透明度的取值
				if(attr =="opacity"){
					obj.style.opacity = Target/100;
				}else{
					obj.style[attr] = Target + "px";
				}
		//动画终止清除定时器
				clearInterval(obj.timer);
			}else{//动画不终止
				//处理透明度和非透明度的取值
				if(attr =="opacity"){
					obj.style.opacity = (currentVal + iSpeed)/100;
				}else{
					obj.style[attr] = currentVal + iSpeed + "px";
				}
			}
		},30)
	}
	var oBox1 = document.getElementById("box1");
	var oBox2 = document.getElementById("box2");
	var oBox3 = document.getElementById("box3");
	oBox1.onmouseover = function(){
		animation(oBox1,"width",300);
	}

	oBox1.onmouseout = function(){
		animation(oBox1,"width",100);
	}

	oBox2.onmouseover = function(){
		animation(oBox2,"height",300);
	}
	oBox2.onmouseout = function(){
		animation(oBox2,"height",100);
	}

	oBox3.onmouseover = function(){
		animation(oBox3,"opacity",100)
	}
	oBox3.onmouseout = function(){
		animation(oBox3,"opacity",30)
	}

</script>
</html>